using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using CodRevit.ViewModels;
using CodRevit.Views;
using CodRevit.Handlers;
using System;
using System.Collections.Generic;
using System.Linq;

namespace CodRevit.Commands
{
    /// <summary>
    /// 导出明细表到Excel命令
    /// 允许用户选择多个明细表并导出到Excel文件
    /// </summary>
    [Transaction(TransactionMode.Manual)]
    public class ExportScheduleCommand : IExternalCommand
    {
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            try
            {
                // 获取当前文档和界面应用程序
                UIApplication uiapp = commandData.Application;
                UIDocument uidoc = uiapp.ActiveUIDocument;
                Document doc = uidoc.Document;

                // 检查是否为项目文档
                if (doc.IsFamilyDocument)
                {
                    TaskDialog.Show("错误", "此命令只能在项目文档中使用。");
                    return Result.Failed;
                }

                // 获取项目中的所有明细表
                var schedules = new FilteredElementCollector(doc)
                    .OfClass(typeof(ViewSchedule))
                    .Cast<ViewSchedule>()
                    .Where(s => !s.IsTemplate) // 排除明细表模板
                    .ToList();

                if (!schedules.Any())
                {
                    TaskDialog.Show("提示", "项目中没有找到明细表。");
                    return Result.Cancelled;
                }

                // 创建ExternalEvent和Handler
                var exportHandler = new ExportScheduleHandler(uiapp);
                var externalEvent = ExternalEvent.Create(exportHandler);

                // 创建窗口和ViewModel
                var window = new ExportScheduleView();
                var viewModel = new ExportScheduleViewModel(uiapp, externalEvent, exportHandler, schedules);

                window.DataContext = viewModel;

                var positionedWindow = App.LeftTopWindow(commandData, window);
                if (positionedWindow == null || positionedWindow is not ExportScheduleView)
                {
                    return Result.Failed;
                }
                window = (ExportScheduleView)positionedWindow;
                window.Show();
                return Result.Succeeded;
            }
            catch (Exception ex)
            {
                TaskDialog.Show("错误", $"执行命令时发生错误：{ex.Message}");
                return Result.Failed;
            }
        }
    }
}